<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>电力消费数据分析</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    <style>
        /* 自定义表格样式 */
        .history-table {
            width: 95%
            margin: 0 auto;
            font-size: 1.05rem;
        }
        .history-table th {
            background-color: #0d6efd;
            color: white;
            font-weight: 500;
        }
        .action-buttons .btn {
            margin: 0 3px;
            padding: 0.25rem 0.5rem;
            font-size: 0.9rem;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top">
        <div class="container">
            <a class="navbar-brand fw-bold" href="#">
                <i class="bi bi-lightning-charge me-2"></i>电力消费数据历史记录表
            </a>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item"></li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link" href="#data-analysis" id="dataAnalysisTab">
                            <i class="bi bi-graph-up me-1"></i>数据分析
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#data-forecast" id="dataForecastTab">
                            <i class="bi bi-magic me-1"></i>数据预测
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#history" id="historyTab">
                            <i class="bi bi-clock-history me-1"></i>历史记录
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-5 pt-4">
        <h1 class="text-left mb-4">电力消费数据历史记录表</h1>
        <div class="row justify-content-center">  <!-- 添加居中布局 -->
            <div class="col-md-12">  <!-- 扩大列宽 -->
                <div class="card">
                    <div class="card-body p-4">  <!-- 增加内边距 -->
                        <div class="table-responsive">
                            <table class="table table-striped table-hover history-table">
                                <thead>
                                    <tr class="text-center">
                                        <th width="35%">文件名</th>
                                        <th width="30%">上传时间</th>
                                        <th width="35%">操作</th>
                                    </tr>
                                </thead>
                                <tbody id="fileTableBody">

                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="{{ url_for('static', filename='js/scripts.js') }}"></script>
    <script>
        document.getElementById('dataAnalysisTab').addEventListener('click', function() {
            window.location.href = "{{ url_for('data_analysis') }}";
        });

        document.getElementById('dataForecastTab').addEventListener('click', function() {
            window.location.href = "{{ url_for('data_yuce') }}";
        });

        document.getElementById('historyTab').addEventListener('click', function() {
            window.location.href = "{{ url_for('data_history') }}";
        });

        // 加载文件数据
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM已加载，开始获取数据...');

    fetch('/api/files')
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP错误! 状态码: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('获取到的数据:', data);
            if (data.status === 'success') {
                renderFileTable(data.data);
            } else {
                throw new Error(data.message || '未知错误');
            }
        })
        .catch(error => {
            console.error('获取数据失败:', error);
            alert('加载数据失败: ' + error.message);
        });
});

// 渲染表格函数
function renderFileTable(files) {
    const tableBody = document.getElementById('fileTableBody');

    if (!tableBody) {
        console.error('错误: 找不到表格容器 #fileTableBody');
        return;
    }

    console.log('开始渲染表格，数据量:', files.length);

    // 清空现有内容
    tableBody.innerHTML = '';

    // 创建文档片段提高性能
    const fragment = document.createDocumentFragment();

    files.forEach(file => {
        const row = document.createElement('tr');

        // 文件名列
        const nameCell = document.createElement('td');
        nameCell.className = 'align-middle text-center';
        nameCell.textContent = file.filename;

        // 上传时间列
        const timeCell = document.createElement('td');
        timeCell.className = 'align-middle text-center';
        timeCell.textContent = file.formatted_time;

        // 操作列
        const actionCell = document.createElement('td');
        actionCell.className = 'text-center action-buttons';

        // 查看详情按钮
        const detailBtn = document.createElement('a');
        detailBtn.href = `/detail/${file.id}`;
        detailBtn.className = 'btn btn-primary btn-sm';
        detailBtn.innerHTML = '<i class="bi bi-eye-fill"></i> 查看详情';

        // 删除按钮
        const deleteBtn = document.createElement('button');
        deleteBtn.className = 'btn btn-danger btn-sm';
        deleteBtn.dataset.id = file.id;  // 使用dataset存储ID
        deleteBtn.innerHTML = '<i class="bi bi-trash"></i> 删除';
        deleteBtn.addEventListener('click', function() {
            deleteFile(file.id, this);
        });

        actionCell.appendChild(detailBtn);
        actionCell.appendChild(deleteBtn);

        row.appendChild(nameCell);
        row.appendChild(timeCell);
        row.appendChild(actionCell);

        fragment.appendChild(row);
    });

    tableBody.appendChild(fragment);
    console.log('表格渲染完成');
}

// 删除文件函数
function deleteFile(fileId, button) {
    if (confirm(`确定要删除这个文件吗？`)) {
        console.log('正在删除文件ID:', fileId);

        fetch(`/api/files/${fileId}`, {
            method: 'DELETE'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`删除失败，状态码: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                button.closest('tr').remove();
                alert('删除成功');
            } else {
                throw new Error(data.message || '删除失败');
            }
        })
        .catch(error => {
            console.error('删除错误:', error);
            alert('删除失败: ' + error.message);
        });
    }
}
    </script>
</body>
<footer class="footer mt-auto py-3 bg-light">
    <div class="container text-center">
        <span class="text-muted">© 2025电力消费数据分析系统</span>
    </div>
</footer>
</html>